//
//  FileManage.swift
//  Extend
//
//  Created by 郑浩 on 2017/10/16.
//  Copyright © 2017年 敬信. All rights reserved.
//

import UIKit

public class FileManage: NSObject {
    public static let share = FileManage.init()
    private override init() {}
    
    var fileManager = FileManager()
    
    /// 创建文件夹
    ///
    /// - Parameter aFolderPath: 文件夹路径
    public func createFolder(aFolderPath: String) {
        //判断文件夹是否存在
        let exist = fileManager.fileExists(atPath: aFolderPath)
        if !exist {
            try! fileManager.createDirectory(atPath: aFolderPath, withIntermediateDirectories: true, attributes: nil)
        }
    }
    
    
    /// 判断路径下的文件是否存在
    ///
    /// - Parameter aFilePath: 文件路径
    public func isFileExit(aFilePath: String) -> Bool {
        return fileManager.fileExists(atPath: aFilePath)
    }
    
    /// 删除文件
    ///
    /// - Parameter aFilePath: 文件路径
    public func deleteFile(aFilePath: String) {
        let exist = fileManager.fileExists(atPath: aFilePath)
        if exist {
            try! fileManager.removeItem(atPath: aFilePath)
        }
    }
    
    
    /// 删除文件夹下所有文件
    ///
    /// - Parameter floderPath: 文件夹路径
    public func deleteFilesByFolder(floderPath: String) {
        var myDirectoryEnumerator: FileManager.DirectoryEnumerator?
        myDirectoryEnumerator = fileManager.enumerator(atPath: floderPath) as? FileManager.DirectoryEnumerator
        
        let enumerator:FileManager.DirectoryEnumerator! = fileManager.enumerator(atPath: floderPath)
        while let element = enumerator?.nextObject() as? String {
              print("删除了文件：\(floderPath + "/" + element)")
              try? fileManager.removeItem(atPath: floderPath + "/" + element)
        }
    }
    
    
    /// 修改文件的文件名,不修改扩展名
    ///
    /// - Parameters:
    ///   - originalPath: 原始文件的文件路径
    ///   - modifiedPath: 被修改的文件路径
    public func renameFileNameWithOutEx(originalPath: String, modifiedPath: String) {
        var originalName = originalPath as NSString
        var modifiedName = modifiedPath as NSString
        
        //原始文件的扩展名
        let exName = originalName.pathExtension
        //要修改成的文件名
        modifiedName = modifiedName.deletingPathExtension as NSString
        let correctPath = modifiedName.appending(".").appending(exName)
        
        //先交换文件名称（包含扩展名）
        try? fileManager.moveItem(atPath: originalPath, toPath: modifiedPath)
        //再交换回正确的文件名称
        try? fileManager.moveItem(atPath: modifiedPath, toPath: correctPath)
    }
}
